﻿using AutoMapper;
using B.T.BasicData.Domain.RBAC;
using B.T.BasicData.ErrorCode;
using B.T.BasicData.Infraeturcture;
using B.T.BasicData.Read.Api.DTOs;
using B.T.BasicData.Read.Api.RBACServices.IServices;
using Microsoft.EntityFrameworkCore;

namespace B.T.BasicData.Read.Api.RBACServices.Services
{
    public class PermissionsServices : IPermissionsServices
    {
        private readonly IBaseRepository<User_Role> userRoleRepository;
        private readonly IBaseRepository<Role_Permission> rolePermissionRepository;
        private readonly IBaseRepository<Permissions> permissionRepository;
        private readonly ILogger<PermissionsServices> logger;
        private readonly IMapper mapper;

        public PermissionsServices(IBaseRepository<User_Role> userRoleRepository,
                                  IBaseRepository<Role_Permission> rolePermissionRepository,
                                  IBaseRepository<Permissions> permissionRepository,
                                  ILogger<PermissionsServices> logger,IMapper mapper)
        {
            this.userRoleRepository = userRoleRepository;
            this.rolePermissionRepository = rolePermissionRepository;
            this.permissionRepository = permissionRepository;
            this.logger = logger;
            this.mapper = mapper;
        }

        /// <summary>
        /// 根据用户ID获取菜单树
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<MenuDto> GetMenuTreeByUserId(long userId)
        {
            try
            {
                // 1. 获取用户角色
                var userRoles = userRoleRepository.Getlist().Where(x => x.UserId == userId && !x.IsDele).ToList();
                var roleIds = userRoles.Select(x => x.RolesId).ToList();

                // 2. 获取角色对应的菜单权限
                var rolePermissions = rolePermissionRepository.Getlist().Where(x => roleIds.Contains(x.RolesId) && !x.IsDele).ToList();
                var permissionIds = rolePermissions.Select(x => x.PermissionsId).Distinct().ToList();

                // 3. 获取菜单数据
                var menus = permissionRepository.Getlist().Where(x => permissionIds.Contains(x.PermissionsId) && !x.IsDeleted).ToList();

                // 4. 转为MenuDto
                var menuDtos = menus.Select(m => new MenuDto
                {
                    Id = m.PermissionsId,
                    Name = m.PermissionName,
                    Path = m.Component, // 或者你菜单的路由字段
                    ParentId = m.Parentnumber // 修正为Parentnumber
                }).ToList();

                // 5. 组装树结构
                return BuildMenuTree(menuDtos, null);
            }
            catch (Exception ex)
            {

                logger.LogError("=>" + ex.Message);
                throw ex;
            }
        }


        /// <summary>
        /// 递归组装树
        /// </summary>
        /// <param name="menus"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private List<MenuDto> BuildMenuTree(List<MenuDto> menus, int? parentId)
        {
            try
            {
                return menus.Where(m => m.ParentId == parentId)
                       .Select(m => {
                           m.Children = BuildMenuTree(menus, m.Id);
                           return m;
                       }).ToList();
            }
            catch (Exception ex)
            {

                logger.LogError("=>" + ex.Message);
                throw ex;
            }
        }


        /// <summary>
        /// 获取级联信息
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<List<TreeshapeDto>>> SearchTreeshape()
        {
            try
            {
                logger.LogInformation("获取级联信息操作");

                var res=new ApiResult<List<TreeshapeDto>>();

                res.success(GetSearchTreeshape(null));
                res.msg = "获取级联数据成功";
                return res;


            }
            catch (Exception ex)
            {

                logger.LogError("=>" + ex.Message);
                throw ex;
            }
        }

        private List<TreeshapeDto> GetSearchTreeshape(int? Parentnumber)
        {
            try
            {
                var info = permissionRepository.Getlist().Where(x =>x.Parentnumber.Equals(Parentnumber));


                var model=mapper.Map<List<TreeshapeDto>>(info);

                foreach(var item in model)
                {
                    item.children = GetSearchTreeshape(item.PermissionsId);
                }

                return model;

            }
            catch (Exception ex)
            {

                logger.LogError("=>" + ex.Message);
                throw ex;
            }
        }
    }
}
